package cn.tworice.system.service.system;

import cn.tworice.common.util.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.*;
import java.net.URLDecoder;

@Service
@Slf4j
public class SystemServiceImpl implements SystemService {

    @Resource
    private DataSource dataSource;

    @Override
    public void recoveryBySQLResource() throws UnsupportedEncodingException {
        String resourcePath = URLDecoder.decode(this.getClass().getClassLoader().getResource("").getPath(), "UTF-8");
        resourcePath = resourcePath + File.separator + "recovery" + File.separator + "recovery.sql";
        this.recoveryBySQLResource(resourcePath);
    }

    @Override
    public void recoveryBySQLResource(String sqlPath) {
        try {
            log.debug("数据库恢复："+sqlPath);
            String sql = FileUtils.readFile(sqlPath);
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] statements = sql.split(";");
            for (String statement : statements) {
                if (!statement.trim().isEmpty()) {
                    jdbcTemplate.execute(statement);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
